package hu.rsc.feeds.server;

import hu.rsc.feeds.client.data.GeneratedFeed;
import hu.rsc.feeds.client.data.SystemFeed;
import hu.rsc.feeds.client.data.UserInfo;

import java.util.Date;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jdom.output.XMLOutputter;
import org.jdom.transform.XSLTransformException;
import org.jdom.transform.XSLTransformer;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;

public class WhatIsNewServlet extends HttpServlet {

    private static final long serialVersionUID = 1268908910096781069L;

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) {
	String app = request.getParameter("app");
	String lang = request.getParameter("lang");
	if (lang == null) {
	    lang = UserInfo.LANG_EN;
	}

	final DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
	GeneratedFeed feed = new GeneratedFeed();
	feed.setAuthor("Red Staff Corporation");
	feed.setTitle("Feed is not available.");

	final Query query = new Query(RssReaderServiceImpl.TABLE_SYSTEM_FEED);
	query.addFilter(SystemFeed.PROP_APPLICATION, Query.FilterOperator.EQUAL, app);
	query.addFilter(SystemFeed.PROP_ISHELP, Query.FilterOperator.EQUAL, new Boolean(false));
	if (lang != null && lang.length() > 0) {
	    query.addFilter(SystemFeed.PROP_LANGUAGE, Query.FilterOperator.EQUAL, lang);
	}
	PreparedQuery pq = datastore.prepare(query);

	for (Entity e : pq.asIterable()) {
	    feed.setId(e.getKey().getId());
	    feed.setPubDate(new Date());
	    feed.setTitle(app);
	}
	AtomGenerator ag = new AtomGenerator(feed, false);

	XMLOutputter outputter = new XMLOutputter();
	//response.setContentType("text/xml");
	response.setContentType("text/html");
	try {
	    XSLTransformer transformer = null;
	    try {
		transformer = new XSLTransformer("whatisnew_" + lang + ".xsl");
	    } catch (XSLTransformException e1) {
		e1.printStackTrace();
	    }
	    outputter.output(transformer.transform(ag.getDocument()), response.getOutputStream());
	} catch (Exception e) {
	    // TODO Auto-generated catch block
	    e.printStackTrace();
	}
    }

}
